package br.com.caiocarrara.goodbuy.controller;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;

import java.io.File;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;
import br.com.caelum.vraptor.validator.Validations;
import br.com.caiocarrara.goodbuy.model.Product;
import br.com.caiocarrara.goodbuy.model.images.Images;

@Resource
public class ImagesController {
	private final Validator validator;
	private final Images images;
	private final Result result;

	public ImagesController(Validator validator, Images images, Result result) {
		this.validator = validator;
		this.images = images;
		this.result = result;
	}

	@Post("/products/{product.id}/image")
	public void upload(Product product, final UploadedFile image) {		
		this.validator.checking(new Validations() {
			{
				if (that(image, is(notNullValue()), "image", "Image null"))
					that(image.getContentType(), startsWith("image"), "image", "File is note image");
				
			}
		});

		this.validator.onErrorRedirectTo(ProductsController.class).editForm(product.getId());

		this.images.save(image, product);
		this.result.redirectTo(ProductsController.class).editForm(product.getId());
	}
	
	@Get("/products/{product.id}/image")
	public File download(Product product) {
		return images.load(product);
	}
	
}
